package package02;

import org.junit.Test;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description 读取文件数据，并创建flow对象
 * @Author zzj
 * @Date 2020/7/17 17:42
 */
public class FlowUtils {
    // 读取文件
    private FlowDao fd = null;
    private Flow flow = null;
    int index =1;

    /**
    * @Description 读取flow.log文件，将每行数据处理后放在字符串数组中
    * @param
    * @Return void
    * @Author zzj
    * @Date 2020/7/18 14:42
    **/
    @Test
    public void readFile() {
        String path = "D:\\flow.log";
        // 声明流
        FileReader fr = null;
        BufferedReader reader = null;
        try {
            fr = new FileReader(path);

            reader = new BufferedReader(fr);

            String line;

            // 读取每一行
            while ((line = reader.readLine()) != null) {
                //System.out.println(line);
                // 去掉空格和制表符
                line = line.replace(" ", "");
                String[] split = line.split("\t");
                StrToList(split);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fr.close();
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return;
    }

    /**
    * @Description 传入字符串数组，将元素放到集合中
    * @param split
    * @Return void
    * @Author zzj
    * @Date 2020/7/18 14:46
    **/
    public void StrToList(String[] split) {
        List<String> list = new ArrayList<>();
        list.add(0, split[0]);
        list.add(1, split[1]);
        list.add(2, split[3]);
        list.add(3, split[4]);
        list.add(4, split[8]);
        list.add(5, split[9]);
        list.add(6, split[10]);

        try {
             // 创建flow对象
            Flow flow = createFlow(list);
            FlowDao fd = new FlowDaoImp();
            // 调用save方法，将flow对象的属性值存储到数据库中
            fd.save(flow,index);
            index++;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
    * @Description 根据集合内容创建flow对象
    * @param list
    * @Return package02.Flow
    * @Author zzj
    * @Date 2020/7/18 14:47
    **/
    public Flow createFlow(List list) throws Exception {
        Flow f = new Flow();
        Date date = new Date(Long.parseLong(list.get(0).toString()));
        //System.out.println(date);
        // 对象初始化
        f.setAccessTime(date);
        f.setPhone(list.get(1).toString());
        f.setSrc(list.get(2).toString());
        f.setUrl(list.get(3).toString());
        f.setUpStream(Integer.parseInt(list.get(4).toString()));
        f.setDownStream(Integer.parseInt(list.get(5).toString()));
        f.setStatus(list.get(6).toString());

        //System.out.println(f);
        return f;
    }


}
